﻿using Aliyun.OSS.Common;
using Aliyun.OSS;
using System.Diagnostics;
using XServer.Models.OSS;
using System.Net;

namespace XServer.Utility
{
    public class OssHelper
    {
        /// <summary>
        /// 校验文件是否存在
        /// </summary>
        /// <param name="oss">配置</param>
        /// <param name="key">文件路径</param>
        /// <returns></returns>
        public static bool CheckObjectExist(OssConfig oss, string key)
        {
            var client = new OssClient(oss.EndPoint, oss.KeyId, oss.Secret);
            var isEx = client.DoesObjectExist(oss.Bucket, key);
            return isEx;

            //Debug.WriteLine("Check object failed, {0}", ex.Message);
        }

        /// <summary>
        /// 上传壁纸
        /// </summary>
        /// <param name="oss">配置</param>
        /// <param name="key">目标路径</param>
        /// <param name="localFile">本地路径</param>
        /// <returns></returns>
        public static bool PutObject(OssConfig oss, string key, string localFile)
        {
            var client = new OssClient(oss.EndPoint, oss.KeyId, oss.Secret);
            var res = client.PutObject(oss.Bucket, key, localFile);
            if (res.HttpStatusCode != HttpStatusCode.OK)
            {
                return false;
            }
            return true;

            //Debug.WriteLine("Put object failed, {0}", ex.Message);
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="oss">配置</param>
        /// <param name="key">路径</param>
        /// <returns></returns>
        public static byte[]? GetObject(OssConfig oss, string key)
        {
            var conf = new ClientConfiguration();
            //// 设置最大并发连接数。
            //ClientConfiguration.ConnectionLimit = 512;
            //// 设置请求失败后最大的重试次数。
            //conf.MaxErrorRetry = 3;
            // 设置连接超时时间。
            //conf.ConnectionTimeout = 300;

            var client = new OssClient(oss.EndPoint, oss.KeyId, oss.Secret, conf);

            var result = client.GetObject(oss.Bucket, key);
            using var requestStream = result.Content;
            using MemoryStream ms = new();

            requestStream.CopyTo(ms);
            byte[] data = ms.ToArray();
            return data;

            //catch (OssException ex)
            //Debug.WriteLine(string.Format("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
            //    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId));

            //catch (Exception ex)
            //Debug.WriteLine(string.Format("Failed with error info: {0}", ex.Message));
        }

        /// <summary>
        /// 获取文件列表
        /// </summary>
        /// <param name="oss"></param>
        /// <returns></returns>
        public static string[]? ListObject(OssConfig oss)
        {
            IList<string> list = [];
            var client = new OssClient(oss.EndPoint, oss.KeyId, oss.Secret);

            ObjectListing? result = null;
            string nextMarker = oss.PathFilter;
            do
            {
                var listObjectsRequest = new ListObjectsRequest(oss.Bucket)
                {
                    Marker = nextMarker,
                    Prefix = oss.PathFilter,
                    //Delimiter = "/"
                };
                // 列举文件。
                result = client.ListObjects(listObjectsRequest);
                foreach (var summary in result.ObjectSummaries)
                {
                    Debug.WriteLine(summary.Key);
                    list.Add(summary.Key);
                }
                nextMarker = result.NextMarker;
            } while (result.IsTruncated);

            return [.. list];
        }
    }
}
